package inCode;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.RandomAccessFile;

import javax.swing.JProgressBar;

public class InCode implements CodeInterface {
	private String s1=null;
	private String s2=null;
	private int code;
	public void codeMethod(JProgressBar bar) {
		try{
			long currentSize=0;
			File file=new File(s1);
			long size=file.length();
			byte[] bt=new byte[1024];
			int s=0;
			FileInputStream fis=new FileInputStream(file);
			FileOutputStream fos=new FileOutputStream(s2);
			try {
				while((s=fis.read(bt))>0){
					currentSize+=s;
					for(int i=0;i<1024;i++){
						fos.write(bt[i]^code);
					}
					bar.setValue((int)(100*currentSize/size));
				}
			}finally{
				fos.close();fis.close();	
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public void setS1(String s){
		this.s1=s;
	}
	public void setS2(String s){
		this.s2=s;
	}
	public void setCode(int n){
		code=n;
	}
}

class InCode2 implements CodeInterface {
	private String s1=null;
	private String s2=null;
	private int code=0;
	public void codeMethod(JProgressBar bar) {
		try{
			long currentSize=0;
			File f=new File(s1);
			FilenameFilter filter=new FilenameFilter(){
				public boolean accept(File dir, String name) {
					if(name.matches(".+\\.jpg$")||name.matches(".+\\.gif$")||name.matches(".+\\.bmp$")||name.matches(".+\\.png&")||name.matches(".+\\.JPG$")){
						return true;
					}
					return false;
				}
			};
			File[] fi=null;
			if(f.isDirectory()){
			    fi=f.listFiles(filter);
			}else{
				fi=new File[1];
				fi[0]=f;
			}
			long size=0;
			for(int i=0;i<fi.length;i++){
				size+=fi[i].length();
			}
			int s=0;
			for(int i=0;i<fi.length;i++){
				byte[] bt=new byte[1024];
				RandomAccessFile raf=new RandomAccessFile(fi[i],"rw");
				try {
					while((s=raf.read(bt))>0){
						currentSize+=s;
						raf.seek(raf.getFilePointer()-s);
						for(int j=0;j<1024;j++){
							raf.write(bt[j]^code);
						}
						bar.setValue((int)(100*currentSize/size));
					}
				}finally{
					raf.close();
					bar.setValue(0);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public void setS1(String s){
		this.s1=s;
	}
	public void setS2(String s){
		s2=s;
	}
	public void setCode(int n){
		code=n;
	}
}

